import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

/**
 * Creates an SWT Table which is meant to use as protocol as file Rename
 * processes.
 * 
 * @author Albert
 * 
 */
public class ProtocolTable {

	private Table table;

	private List<String> currentProtocol = new ArrayList<String>();
	private Display display;

	/**
	 * Creates a table protocol. Which is just a list with 1 column.
	 * 
	 * @param shell
	 *            The shell where to render it.
	 * @param display the display where to render it.
	 */
	public ProtocolTable(Shell shell, Display display) {
		this.display = display;

		table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
		table.addListener(SWT.SetData, new Listener() {
			public void handleEvent(Event e) {
				TableItem from = (TableItem) e.item;
				int index = table.indexOf(from);
				from.setText(currentProtocol.get(index));

			}
		});

		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
		gridData.horizontalSpan = 3;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		table.setLayoutData(gridData);
	}

	/**
	 * If you call this method, you will add two new entries into the list. One
	 * represents the old file name. The other represents the new file name.
	 * 
	 * @param from
	 *            old file name.
	 * @param to
	 *            new file name
	 */
	public void addProtocoll(String from, String to) {
		currentProtocol.add("FROM: \"" + from + "\"");
		currentProtocol.add("  -TO: \"" + to + "\"");

		// update the Table
		display.syncExec(new Runnable() {
			public void run() {
				if (table.isDisposed())
					return;
				table.setItemCount(currentProtocol.size());
				table.clearAll();
			}
		});
	}

	public void clear() {
		currentProtocol.clear();
		display.syncExec(new Runnable() {
			@Override
			public void run() {
				table.removeAll();
			}
		});
	}
}
